/**
 * MySQL元数据代码生成页面JS
 * User: zhaoming
 * Date: 201616-07-05
 * Time: 下午5:58
 * To change this template use File | Settings | File Templates.
 */
$(function(){

    //激活左侧导航
    activeNavBar("mysqlGenerator", "analyze");

    initDatabaseData();

    //加载数据列表
    loadGrid();

    //重置数据列表宽度
    $("#gridTableWidgetBody").resize(function(){
        $("#gridTable").setGridWidth($(this).width(), false);
    });

    $('#tableSchema').change(function() {
        //初始化数据
        $("#tableName").empty();
        $("#tableName").append("<option value=''>请选择</option>");
        $("#tableName").select2("val", "");
        $("#tableComment").val("");
        clear();

        var tableSchema = $(this).val();
        if(tableSchema != ""){
            selectTableNames(tableSchema);
        }
    });

    $('#tableName').change(function() {
        $("#tableComment").val("");
        clear();

        if($(this).val() != ""){
            query();
        }
        var tableName = $(this).find('option:selected').text();
        var tableComment = $(this).find('option:selected').attr("tableComment");
        $("#tableComment").val(tableComment);

        if(tableName.indexOf("_")>0) {
            $("#tablePrefix").val(tableName.substring(0, tableName.indexOf("_")));
        }
    });

    $("#generator").click(function(){
        generator();
    });
});

/**
 * 初始化数据库列表
 */
function initDatabaseData(){
    jQuery.ajax({
        type:"POST",
        dataType:'json',
        url: "/web/mysqlGenerator/selectDatabase",
        success:function (data) {
            $("#tableSchema").empty();
            $("#tableSchema").append("<option value=''>请选择</option>");
            $("#tableSchema").select2("val", "");
            for (var i = 0; i < data.length; i++) {
                $("#tableSchema").append("<option value='" + data[i].tableSchema + "'>" + data[i].tableSchema + "</option>");
            }
        },
        error : function(data){
            Commons.showError(data.responseText);
        }
    });
}

/**
 * 获取数据表
 */
function selectTableNames(tableSchema){
    jQuery.ajax({
        type : "POST",
        dataType:'json',
        url : "/web/mysqlGenerator/selectTableNames",
        data : {
            tableSchema: tableSchema
        },
        success : function(data) {
            for(var i=0; i<data.length; i++){
                $("#tableName").append("<option value='"+data[i].tableName+"' tableComment='"+data[i].tableComment+"'>"+data[i].tableName+"</option>");
            }
        },
        error: function (data) {
            Commons.showError(data.responseText);
        }
    });
}

/**
 * 加载数据列表
 */
var lastSelectId;
function loadGrid(){
    var gridTable = jQuery("#gridTable");
    gridTable.jqGrid({
        mtype:"POST",
        datatype: "json",
        autowidth: true,
        height: "300",
        colModel:[
            {name:'columnKey',label:'主键', hidden:true},
            {name:'extra',label:'主键策略', hidden:true},
            {name:'tableSchema',label:'数据库名', width:100, fixed:false, sortable: false, align:'center', hidden:true},
            {name:'tableName',label:'数据表名', width:100, fixed:false, sortable: false, align:'center', hidden:true},
            {name:'columnName',label:'字段名称', width:100, fixed:false, sortable: false, align:'center'},
            {name:'columnComment',label:'字段描述', width:100, fixed:false, sortable: false, align:'center', editable : true},
            {name:'dataType',label:'数据类型', width:100, fixed:false, sortable: false, align:'center'},
            {name:'uniqueFlag',label:'唯一标识', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "checkbox",
                editoptions: {
                    value: "是:"
                },
                formatter: function (cellValue, options, rowObject) {
                    var result = "";
                    if(rowObject.columnName == "unique_no"){
                        result = "是";
                    }
                    return result;
                }
            },
            {name:'likeFlag',label:'模糊标识', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "checkbox",
                editoptions: {
                    value: "是:"
                }
            },
            {name:'extFlag',label:'扩展标识', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "checkbox",
                editoptions: {
                    value: "是:"
                },
                formatter: function (cellValue, options, rowObject) {
                    var result = "";
                    if(rowObject.columnName == "create_user_no"){
                        result = "是";
                    }else if(rowObject.columnName == "create_user_name"){
                        result = "是";
                    }else if(rowObject.columnName == "create_time"){
                        result = "是";
                    }else if(rowObject.columnName == "update_user_no"){
                        result = "是";
                    }else if(rowObject.columnName == "update_user_name"){
                        result = "是";
                    }else if(rowObject.columnName == "update_time"){
                        result = "是";
                    }
                    return result;
                }
            },
            {name:'effectiveFlag',label:'逻辑标识', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "checkbox",
                editoptions: {
                    value: "是:"
                },
                formatter: function (cellValue, options, rowObject) {
                    var result = "";
                    if(rowObject.columnName == "is_delete"){
                        result = "是";
                    }
                    return result;
                }
            },
            {name:'filterFlag',label:'过滤标识', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "checkbox",
                editoptions: {
                    value: "是:"
                }
            },
            {name:'autoFill',label:'自动填充', width:80, fixed:false, sortable: false, align:'center',
                editable : true,
                edittype: "select",
                editoptions: {
                    value : ":;CREATER_CODE:CREATER_CODE;CREATER_NAME:CREATER_NAME;CREATE_TIME:CREATE_TIME;OPERATOR_CODE:OPERATOR_CODE;OPERATOR_NAME:OPERATOR_NAME;OPERATE_TIME:OPERATE_TIME"
                },
                formatter: function (cellValue, options, rowObject) {
                    var result = "";
                    if(rowObject.columnName == "create_user_no"){
                        result = "CREATER_CODE";
                    }else if(rowObject.columnName == "create_user_name"){
                        result = "CREATER_NAME";
                    }else if(rowObject.columnName == "create_time"){
                        result = "CREATE_TIME";
                    }else if(rowObject.columnName == "update_user_no"){
                        result = "OPERATOR_CODE";
                    }else if(rowObject.columnName == "update_user_name"){
                        result = "OPERATOR_NAME";
                    }else if(rowObject.columnName == "update_time"){
                        result = "OPERATE_TIME";
                    }
                    return result;
                }
            }
        ],
        rownumbers:true,//添加左侧行号
        viewrecords : true,
        rowNum:1000,
        altRows: true,
        //altclass: "",
        pager : "#gridPager",
        jsonReader: {
            root: "root", //对于json中数据列表
        },
        onSelectRow : function(id) {
            if (id && id !== lastSelectId) {
                gridTable.jqGrid('saveRow', lastSelectId, false, 'clientArray');
                gridTable.jqGrid('editRow', id, false);
                lastSelectId = id;
            }
        }
    });
    updatePagerIcons(gridTable);
    gridTable.setGridWidth($("#gridTableWidgetBody").width(), true);
}

/**
 * 查询
 */
function query(){
    var gridParam = {
        url:"/web/mysqlGenerator/selectColumnNames",
        postData:{
            tableSchema : $("#tableSchema").val(),
            tableName : $("#tableName").val()
        },
        page:1
    };
    $("#gridTable").jqGrid("setGridParam", gridParam).trigger("reloadGrid");
}

/**
 * 清除列表数据
 */
function clear(){
    $("#gridTable").jqGrid("clearGridData");

}

/**
 *  代码生成
 */
function generator() {

    $("#gridTable").jqGrid('saveRow', lastSelectId, false, 'clientArray');
    lastSelectId = null;

    if($('#generatorForm').trigger("validate").isValid()){

        var rows = $("#gridTable").jqGrid('getRowData');
        var uniqueFlag = false;
        for(var i = 0; i < rows.length; i++) {
            if (rows[i].columnComment == "" || rows[i].columnComment == null) {
                Commons.showWarn("字段描述不允许为空");
                return;
            }
            if(rows[i].uniqueFlag == "是"){
                uniqueFlag = true;
            }
        }

        if(!uniqueFlag){
            Commons.showWarn("唯一标识不允许为空");
            return;
        }


        $("#columnJson").val(JSON.stringify(rows));
        var m = $('#generatorForm')[0];
        m.method = 'POST';
        m.action = '/web/mysqlGenerator/downLoad';
        m.submit();
    }
}